/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ipfw.cs590.cheat.struts.actions;

import edu.ipfw.cs590.cheat.AssignmentManagementInterface;
import edu.ipfw.cs590.cheat.AssignmentManagementService;
import edu.ipfw.cs590.cheat.DenyRegistrationRequest;
import edu.ipfw.cs590.cheat.GetPendingRegistrationRequests;
import edu.ipfw.cs590.cheat.GrantRegistrationRequest;
import edu.ipfw.cs590.cheat.struts.actionforms.PendingUserManagementForm;
import edu.ipfw.cs590.cheat.util.Authentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author safar
 */
public class PendingUserManagementAction extends DispatchAction {

    private final static String MOD_SUCCESS = "OperationSuccess";
    private final static String LIST_SUCCESS = "GetListSuccess";
    private final static String FAILURE = "failure";

    /**
     * This is the action called when the action=getPendingList.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward getPendingList(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //If the request doesn't have priveleges
        if (!Authentication.isAdmin(request.getSession(false))) {
            response.sendError(response.SC_FORBIDDEN, "Pending User Management.");

            return mapping.findForward(FAILURE);
        }

        //If the form is a pending user management form
        if (form instanceof PendingUserManagementForm) {
            //Get the pending user management form
            PendingUserManagementForm pumf = (PendingUserManagementForm) form;

            //Get a sesion if one doesn't exist
            HttpSession session = request.getSession(false);

            //if we have a session
            if (session != null) {
                try {
                    // Call Web Service Operation
                    AssignmentManagementService service = new AssignmentManagementService();
                    AssignmentManagementInterface port = service.getAssignmentManagementSOAP();
                    //Store the pending users
                    pumf.setPendingUserList(port.getPendingRegistrationRequests(
                            new GetPendingRegistrationRequests(),
                            (String) session.getAttribute(Authentication.SESSION_NAME_TOKEN)).getGetPendingResult());

                    //If the list is empty make a message
                    if (pumf.getPendingUserList().size() == 0) {
                        //Store message for redisplay
                        ActionMessages errors = new ActionMessages();
                        errors.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage("success.service.getPendingList.empty"));
                        this.saveMessages(request, errors);
                    }

                    //We're good return
                    return mapping.findForward(LIST_SUCCESS);
                } catch (Exception exc) {
                    //Something bad happened on the webservice side fail.
                    ActionMessages errors = new ActionMessages();
                    errors.add(ActionMessages.GLOBAL_MESSAGE,
                            new ActionMessage("errors.service.error", "Get Pending Users", exc.getMessage()));
                    this.saveErrors(request, errors);

                    //Return failure.
                    return mapping.getInputForward();
                }
            }

            //Something bad happened on the webservice side fail.
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("errors.service.nosession"));
            this.saveErrors(request, errors);

            //Return failure.
            return mapping.getInputForward();
        }

        //Something bad happened on the webservice side fail.
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.form.invalid"));
        this.saveErrors(request, errors);

        //Epic fail team epic fail
        return mapping.findForward(FAILURE);
    }

    /**
     * This is the action called when the action=grantRequest.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward grantRequests(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //If the request doesn't have priveleges
        if (!Authentication.isAdmin(request.getSession(false))) {
            response.sendError(response.SC_FORBIDDEN, "Pending User Management.");

            return mapping.findForward(FAILURE);
        }

        //If the form is a pending user management form
        if (form instanceof PendingUserManagementForm) {
            //Get the pending user management form
            PendingUserManagementForm pumf = (PendingUserManagementForm) form;

            //Get a sesion if one doesn't exist
            HttpSession session = request.getSession(false);

            //if we have a session
            if (session != null) {
                try {
                    // Call Web Service Operation
                    AssignmentManagementService service = new AssignmentManagementService();
                    AssignmentManagementInterface port = service.getAssignmentManagementSOAP();
                    //Set up the send requests
                    GrantRegistrationRequest req = new GrantRegistrationRequest();
                    req.setPendingUser(pumf.getId());

                    boolean granted = port.grantRegistrationRequest(req,
                            (String) session.getAttribute(Authentication.SESSION_NAME_TOKEN)).isGrantResult();

                    //Grant success
                    if (granted) {
                        //Store message for redisplay
                        ActionMessages errors = new ActionMessages();
                        errors.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage("success.service.grantPendingUser", pumf.getId()));
                        this.saveMessages(request, errors);

                        return mapping.findForward(MOD_SUCCESS);
                    }
                } catch (Exception exc) {
                    //Something bad happened on the webservice side fail.
                    ActionMessages errors = new ActionMessages();
                    errors.add(ActionMessages.GLOBAL_MESSAGE,
                            new ActionMessage("errors.service.error", "Grant Pending Users", exc.getMessage()));
                    this.saveErrors(request, errors);

                    //Return failure.
                    return mapping.findForward(MOD_SUCCESS);
                }
            }

            //no session
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("errors.service.nosession"));
            this.saveMessages(request, errors);

            return mapping.findForward(MOD_SUCCESS);
        }

        //Something bad happened on the webservice side fail.
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.form.invalid"));
        this.saveErrors(request, errors);

        return mapping.findForward(MOD_SUCCESS);
    }

    /**
     * This is the action called when the action=denyRequest.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward denyRequests(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //If the request doesn't have priveleges
        if (!Authentication.isAdmin(request.getSession(false))) {
            response.sendError(response.SC_FORBIDDEN, "Pending User Management.");

            return mapping.findForward(FAILURE);
        }

        //If the form is a pending user management form
        if (form instanceof PendingUserManagementForm) {
            //Get the pending user management form
            PendingUserManagementForm pumf = (PendingUserManagementForm) form;

            //Get a sesion if one doesn't exist
            HttpSession session = request.getSession(false);

            //if we have a session
            if (session != null) {
                try {
                    // Call Web Service Operation
                    AssignmentManagementService service = new AssignmentManagementService();
                    AssignmentManagementInterface port = service.getAssignmentManagementSOAP();
                    DenyRegistrationRequest req = new DenyRegistrationRequest();
                    req.setPendingUser(pumf.getId());

                    boolean denied = port.denyRegistrationRequest(req,
                            (String) session.getAttribute(Authentication.SESSION_NAME_TOKEN)).isDenyResult();

                    if (denied) {
                        //deny success
                        ActionMessages errors = new ActionMessages();
                        errors.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage("success.service.denyPendingUser", pumf.getId()));
                        this.saveMessages(request, errors);

                        return mapping.findForward(MOD_SUCCESS);
                    }
                } catch (Exception exc) {
                    //Something bad happened on the webservice side fail.
                    ActionMessages errors = new ActionMessages();
                    errors.add(ActionMessages.GLOBAL_MESSAGE,
                            new ActionMessage("errors.service.error", "Deny Pending Users", exc.getMessage()));
                    this.saveErrors(request, errors);

                    //Return failure.
                    return mapping.findForward(MOD_SUCCESS);
                }
            }
            //no session
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("errors.service.nosession"));
            this.saveMessages(request, errors);

            return mapping.findForward(MOD_SUCCESS);
        }

        //Something bad happened on the webservice side fail.
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.form.invalid"));
        this.saveErrors(request, errors);

        return mapping.findForward(MOD_SUCCESS);
    }
}